﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Threading;

namespace Derrick.Web
{
    public partial class WebCometClient : System.Web.UI.UserControl
    {
        protected string _postbackScript;
        private Thread _cometThread = null;
        private HttpWebRequest _request;
        private string _receivedMessage;
        private string _sendMessage;
        private string _cometUrl;
        private string _username;
        private string _password;

        public string MessageReceived
        {
            get { return _receivedMessage; }
        }

        public string MessageToSend
        {
            get { return _sendMessage; }
            set { _sendMessage = value; }
        }

        public string PostBackScript
        {
            get { return _postbackScript; }
        }

        public string CometUrl
        {
            get { return _cometUrl; }
            set { _cometUrl = value; }
        }

        public string Username
        {
            get { return _username; }
            set { _username = value; }
        }

        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _postbackScript = Page.ClientScript.GetPostBackEventReference(this, String.Empty);


            //_cometThread = new Thread(new ThreadStart(cometMessageLoop));

            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate
            {
                try
                {
                    cometMessageLoop();
                }
                catch (Exception ex)
                {
                    string error = ex.ToString();
                }
            }));


        }

        protected void doPostBack()
        {

            Page.ClientScript.RegisterClientScriptBlock(GetType(), "MessageReceived", _postbackScript, true);

        }

        private void cometMessageLoop()
        {
            try
            {
                _request = (HttpWebRequest)HttpWebRequest.Create(_cometUrl);

                byte[] bytes;
                System.Text.Encoding enc = System.Text.Encoding.ASCII;
                bytes = enc.GetBytes(_sendMessage);

                _request.SendChunked = false;
                _request.KeepAlive = true;
                _request.Credentials = new NetworkCredential(_username, _password);
                _request.Method = "POST";
                //_request.ContentType = "application/xml";
                _request.ContentType = "text/plain";
                _request.ContentLength = bytes.Length - 3;

                Thread.Sleep(100);
                Stream stream = _request.GetRequestStream();
                stream.Write(bytes, 3, bytes.Length - 3);

                HttpWebResponse res = (HttpWebResponse)_request.GetResponse();
                StreamReader s = new StreamReader(res.GetResponseStream());
                //Console.WriteLine(s.ReadToEnd());
                _receivedMessage = s.ReadToEnd();
                s.Close();
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "MessageReceived", _postbackScript, true);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(e.Message);

            }


        }

        public void SendToCometServer()
        {
            Thread.Sleep(100);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:1802");

            byte[] bytes;
            using (Stream reader = File.OpenRead("Data.xml"))
            {
                bytes = new byte[reader.Length];
                reader.Read(bytes, 0, (int)reader.Length);
            }

            request.SendChunked = false;
            request.KeepAlive = true;
            request.Credentials = new NetworkCredential("server", "server123");
            request.Method = "POST";
            request.ContentType = "application/xml";
            request.ContentLength = bytes.Length - 3;

            Stream stream = request.GetRequestStream();
            stream.Write(bytes, 3, bytes.Length - 3);


            //Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));

            try
            {
                HttpWebResponse res = (HttpWebResponse)request.GetResponse();
                StreamReader s = new StreamReader(res.GetResponseStream());
                //Console.WriteLine(s.ReadToEnd());
                s.Close();
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.Message);

            }
        }
    }
}